﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Presenter.TomoManagement;
using MS.InformationManagement.DAL.DocumentCenter;
using System.Linq;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using Microsoft.SharePoint;
using System.Text;

namespace MS.InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls
{
    public partial class ExpedientePorTomo : BaseControl, ITomoManagementView
    {
        TomoManagementPresenter _presenter;
        Dictionary<string, string> _formUrl;

        public string IdExpediente { get; set; }
        public string IdTomo { get; set; }
        public IEnumerable<Radicado> Radicados { get; set; }
        public Tomo TomoEntity { get; set; }
        public bool EnableAddRemove
        {
            get
            {
                return Convert.ToBoolean(Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "AddRemoveIncludeEnable"]);
            }
            set
            {
                Cache[SPContext.Current.Web.CurrentUser.LoginName.GetUserWithOutDomain() + "AddRemoveIncludeEnable"] = value;
            }
        }

        public int PageIndex
        {
            get
            {
                return pgrPaginador.PageIndex;
            }
            set
            {
                pgrPaginador.PageIndex = value;
            }
        }

        public int PageSize
        {
            get
            {
                return pgrPaginador.PageSize;
            }
            set
            {
                pgrPaginador.PageSize = value;
            }
        }

        public int TotalRecords
        {
            get
            {
                return pgrPaginador.TotalRecords;
            }
            set
            {
                pgrPaginador.TotalRecords = value;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            try
            {
                _formUrl = new Dictionary<string, string>();
                _formUrl = new Dictionary<string, string>();
                _formUrl[GlobalConstants.METADATA_TERM_TIPO_RADICADO_ENTRADA] = "/sites/docs/_layouts/MS.InformationManagement.WP/InsertarRadicado.aspx?strategy=view&List={0}&ID={1}";
                _formUrl[GlobalConstants.METADATA_TERM_TIPO_RADICADO_SALIDA] = "/sites/docs/_layouts/MS.InformationManagement.WP/InsertarRadicadoSalida.aspx?strategy=view&List={0}&ID={1}";
                _formUrl[GlobalConstants.METADATA_TERM_TIPO_INTERNO] = "/sites/docs/_layouts/MS.InformationManagement.WP/RadicadoInterno.aspx?strategy=view&List={0}&ID={1}";
                _presenter = new TomoManagementPresenter(this);

                pgrPaginador.OnPageChanged += new Pager.PageChangeHandler(pgrTemplates_OnPageChanged);
                pgrPaginador.NumberOfPagesToDisplay = 10;
                PageIndex = 0;
                PageSize = 10;

                _presenter.HandleLoad();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public void TomoUpdated()
        {
            HandleSuccess("Tomo actualizado exitosamente", null);
        }

        public void Show()
        {
            try
            {
                txtCaja.Text = TomoEntity.Caja == null ? string.Empty : TomoEntity.Caja;
                txtCara.Text = TomoEntity.Cara == null ? string.Empty : TomoEntity.Cara;
                //txtCarpeta.Text = TomoEntity.Carpeta == null ? string.Empty : TomoEntity.Carpeta;
                txtEntrepanho.Text = TomoEntity.Entrepaño == null ? string.Empty : TomoEntity.Entrepaño;
                txtEstante.Text = TomoEntity.Estante == null ? string.Empty : TomoEntity.Estante;
                txtPiso.Text = TomoEntity.Piso == null ? string.Empty : TomoEntity.Piso;
                lblFechaInicial.Text = TomoEntity.FechaInicial.HasValue ? TomoEntity.FechaInicial.Value.ToString("dd/MM/yyyy hh:mm:ss tt") : string.Empty;
                lblFechaFinal.Text = TomoEntity.FechaFinal.HasValue ? TomoEntity.FechaFinal.Value.ToString("dd/MM/yyyy hh:mm:ss tt") : string.Empty;
                lblTomo.Text = TomoEntity.Title;

                if (Radicados.Count() > 0)
                {
                    var radicadoInicial = Radicados.OrderBy(x => x.Created).First();
                    var radicadoFinal = Radicados.OrderByDescending(x => x.Created).First();
                    lblFechaIniRadicado.Text = radicadoInicial.Created.ToString("dd/MM/yyyy hh:mm:ss tt");
                    lblFechaFinRadicado.Text = radicadoFinal.Created.ToString("dd/MM/yyyy hh:mm:ss tt");

                    this.trFechasRadicados.Visible = true;
                }
                else
                    this.trFechasRadicados.Visible = false;

                lblFolios.Text = Radicados == null ? "0" : Radicados.Count().ToString();

                if (!EnableAddRemove)
                {
                    txtCaja.Enabled = false;
                    txtCara.Enabled = false;
                    txtEntrepanho.Enabled = false;
                    txtEstante.Enabled = false;
                    txtPiso.Enabled = false;

                    btnUpdate.Visible = false;
                }

                PageIndex = 0;
                LoadRadicados();
                pgrPaginador.BuildPager();
                btnExportar.HRef = "javascript:exportVolumeItems" + IdTomo + "();";
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void LoadRadicados()
        {
            try
            {
                gvRadicados.DataSource = Radicados;
                gvRadicados.DataBind();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void getVolume()
        {
            TomoEntity = new Tomo();
            TomoEntity.Caja = txtCaja.Text;
            TomoEntity.Cara = txtCara.Text;
            //TomoEntity.Carpeta = txtCarpeta.Text;
            TomoEntity.Entrepaño = txtEntrepanho.Text;
            TomoEntity.Estante = txtEstante.Text;
            TomoEntity.Piso = txtPiso.Text;
            TomoEntity.Id = int.Parse(IdTomo);
        }

        protected void update_action(object sender, EventArgs e)
        {
            try
            {
                getVolume();
                _presenter.HandleUpdate();
                _presenter.HandleLoad();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void pgrTemplates_OnPageChanged(object sender, Controls.PageChangeEventArgs e)
        {
            _presenter.HandleSearchRadicados();
            LoadRadicados();
            pgrPaginador.BuildPager();
        }

        protected void gvRadicados_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType != DataControlRowType.DataRow) return;
                HyperLink link = e.Row.FindControl("HyperLink1") as HyperLink;
                HyperLink lnkExcluir = e.Row.FindControl("lnkExcluir") as HyperLink;
                HyperLink lnkArchivar = e.Row.FindControl("lnkArchivar") as HyperLink;
                Image imgArchivado = e.Row.FindControl("imgArchivado") as Image;
                Radicado currentItem = e.Row.DataItem as Radicado;
                string expedienteListId = string.Empty;
                string listPadre = string.Empty;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                    {
                        using (SPWeb miWeb = site.OpenWeb())
                        {
                            //expedienteListId = miWeb.Lists.TryGetList(currentItem.ParentExpedienteListName).ID.ToString();
                            expedienteListId = currentItem.ParentExpedienteListName;
                            listPadre = miWeb.Lists[currentItem.ListId].Title;
                        }
                    }
                });

                lnkExcluir.NavigateUrl = string.Format("javascript:openDialogAutoSizeRefreshParent('/sites/docs/_layouts/MS.InformationManagement.WP/ExcludeFileRecord.aspx?RadicadoId={0}&ListName={1}&ExpedienteListName={2}')", currentItem.NoRadicado, listPadre, currentItem.ParentExpedienteListName);
                lnkExcluir.ToolTip = "Excluir de expediente";
                link.NavigateUrl = string.Format("javascript:openDialogAutoSize('" + _formUrl[currentItem.TipoRadicado] + "')", expedienteListId, currentItem.Id.Value);

                if (EnableAddRemove)
                {
                    if (currentItem.Archivado.HasValue && currentItem.Archivado.Value)
                    {
                        imgArchivado.ImageUrl = "/_layouts/images/CbChecked.gif";
                        imgArchivado.ToolTip = "Archivado";
                        lnkArchivar.Visible = false;
                    }
                    else
                    {
                        imgArchivado.ImageUrl = "/_layouts/images/attention16by16.gif";
                        imgArchivado.ToolTip = "Sin Archivar";
                        lnkArchivar.Visible = true;
                        if (currentItem.TipoRadicado == "Radicado Entrada" && (!currentItem.RecibidoInterno.HasValue || !currentItem.RecibidoInterno.Value))
                        {
                            lnkArchivar.ImageUrl = "/_layouts/Images/warning16by16.gif";
                            lnkArchivar.ToolTip = "El documento no ha sido recepcionado físicamente";
                        }
                        else
                            lnkArchivar.NavigateUrl = string.Format("javascript:openDialogAutoSizeRefreshParent('/sites/docs/_layouts/MS.InformationManagement.WP/AddFileToRecord.aspx?RadicadoId={0}&ExpedienteId={1}&ListId={2}')", currentItem.NoRadicado, IdExpediente, expedienteListId);
                    }
                }
                else
                {
                    imgArchivado.Visible = false;
                    lnkArchivar.Visible = false;
                    lnkExcluir.Visible = false;
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }
    }
}
